<?php
/**
 * This controller is responsible for processing actions with plugins
 *
 */
class Backend_PluginController extends RCMS_Core_BaseController {

	const PLUGIN_ENABLED  = 'enabled';

	const PLUGIN_DISABLED = 'disabled';

	protected $_pathPlugin;

	protected $_languageId;

	protected $_languageName;

	protected $_browsePlugins = '';

	public function init() {
		parent::init();
		$this->_checkLogin(array('uploadplugin','fireaction'));
		$this->_model = new Backend_PluginModel();
		$this->_languageId = $this->_session->langId;
		$this->_languageName = $this->_languageId;
		if($this->_languageName == '') {
			$this->_browsePlugins  = 'swf-browse-plugins.png';
		} 
		else {
			$this->_browsePlugins = 'swf-browse-plugins' . '-' . $this->_languageName . '.png';
			if(!file_exists('system/js/swfupload/' . $this->_browsePlugins)) {
				$this->_browsePlugins = 'swf-browse-plugins.png';
			}
		}
		$this->_pathPlugin       = $this->_config->website->website->path . RCMS_Object_QuickConfig_QuickConfig::$pluginsDir;
		$this->_pathThemes       = $this->_config->website->website->path . $this->_config->website->website->themesPath;
		$this->_currentThemeName = $this->_model->selectCurrentTheme();
	}

	/**
	 * Show plugins
	 * 
	 * @return void
	 */
	public function indexAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$listPlugins = RCMS_Tools_FilesystemTools::scanDir($this->_pathPlugin);
		foreach ($listPlugins as $key => $plugin) {
			$result = $this->_model->selectPluginByName($plugin);
			$listPlugins[$key] = array(
				'name'   => $plugin,
				'status' => ($result) ? $result['status'] : 'disabled',
				'cache'  => ($result) ? $result['cache'] : '0',
				'inDb'   => ($result) ? 1: 0
			);
                $listFilesInTheme = RCMS_Tools_FilesystemTools::scanDir($this->_pathPlugin.'/'.$plugin);
				$previewPicture = '';
				foreach ($listFilesInTheme as $file) {
					if(preg_match('/^preview\.(jpg|gif|png)$/', $file) && $previewPicture == '') {
						$previewPicture = $file;
                        $srcPreviewPicture = $this->_config->website->website->url . RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $plugin . '/' . $previewPicture;
                        $listPlugins[$key]['previewImage'] = $srcPreviewPicture;
                        break;
					}
					else {
						$srcPreviewPicture = $this->_config->website->website->url . "system/images/noimage.png";
						$listPlugins[$key]['previewImage'] = $srcPreviewPicture;
					}
				}
		}
		$this->view->success             = $this->getRequest()->getParam('success');
		$this->view->pathPlugin          = $this->_pathPlugin;
		$this->view->browsePlugins       = $this->_browsePlugins;
		$this->view->websiteUrl          = $this->getWebSiteUrl();
		$this->view->listPlugins         = $listPlugins;
		$this->view->zipExtensionEnabled = (extension_loaded('zip') == true ? true : false);
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}


	/**
	 * Show readme.txt
	 * 
	 * @return void
	 */
	public function readmeAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		
		if($this->getRequest()->getParam('pluginName')) {
			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));
			if(file_exists(RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $pluginName . '/readme.txt')) {
				$readmeContent = htmlspecialchars(file_get_contents(RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $pluginName . '/readme.txt'));
				if(trim($readmeContent) == '') {
					$readmeContent = 'Readme.txt for this plugin is empty.';
				}
			}
		}
		$this->view->pluginName    = $pluginName;
		$this->view->readmeContent = $readmeContent;
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	/**
	 * This function uploads a plugin and saves it into the filesystem.
	 * 
	 * @return void
	 */
	public function uploadpluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$file = new Zend_File_Transfer_Adapter_Http();
		$data = $file->getFileInfo();
		$tmpFolder = $this->_config->website->website->path . $this->_config->website->website->tmp;

		$zip = new ZipArchive();
		$zip->open($data['Filedata']['tmp_name']);
		$zip->extractTo($tmpFolder);

		//$this->_overwriteTheme = $this->getRequest()->getParam('overwrite');
		$check = $this->_validatePlugin($tmpFolder);
		$this->_deletePluginFromTmpFolder($tmpFolder);

		if(!empty($check)) {
			$zip->close();
			echo json_encode(array('error' => $check['error'], 'message'=> $check['message']));
			exit();
		}
		else {
			if(is_dir($this->_pathPlugin . $this->_uploadPluginName)) {
				echo json_encode(array('error' => false, 'exist_plugin' => true));
				exit();
			}
			else {
				$zip->extractTo($this->_pathPlugin);
				$zip->close();
				$previewPicture = '';
				$listFilesInTheme = RCMS_Tools_FilesystemTools::scanDir($this->_pathPlugin . $this->_uploadPluginName);
				foreach ($listFilesInTheme as $file) {
					if(preg_match('/^preview\.(jpg|gif|png)$/', $file) && $previewPicture == '') {
						$previewPicture = $file;
						break;
					}
				}
				$path = $this->_pathPlugin . $this->_uploadPluginName;
				if(file_exists($path . '/' .$previewPicture)) {
					$srcPreviewPicture = $this->_config->website->website->url . RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $this->_uploadPluginName . '/' . $previewPicture;
				}
				else {
					$srcPreviewPicture = $this->_config->website->website->url . 'system/images/noimage.png';
				}

				echo json_encode(array('error' => false, 'exist_plugin' => false, 'plugin' => $this->_uploadPluginName, 'preview' => $srcPreviewPicture));
				exit();
			}
		}
	}

	/**
	 * This function checks plugin's folder and returns array of errors.
	 *
	 * @param type $folder
	 * @return array
	 */
	private function _validatePlugin($folder) {
		if(!is_dir($folder)) {
			return array(
				'error'   => true,
				'message' => 'Can not create folder for unpack zip file. 0peration not permitted.'
			);
		}
		$namePlugin = RCMS_Tools_FilesystemTools::scanDir($folder);
		$namePlugin = strtolower($namePlugin[0]);
		$listFiles = RCMS_Tools_FilesystemTools::scanDir($folder . $namePlugin);
		if(empty($listFiles)) {
			return array('error'=>true, 'message'=>'Your plugin directory is empty.');
		}
		if(!file_exists($folder . $namePlugin . '/system/install.sql')) {
			return array('error'=>true, 'message'=>'File "install.sql" doesn\'t exists.');
		}
		if(!file_exists($folder . $namePlugin . '/readme.txt')) {
			return array('error'=>true, 'message'=>'File "readme.txt" doesn\'t exists.');
		}
		if(!file_exists($folder . $namePlugin . '/system/uninstall.sql')) {
			return array('error'=>true, 'message'=>'File "uninstall.sql" doesn\'t exists.');
		}
		if( is_dir($this->_pathPlugin. $namePlugin)) {
			return array('error'=>true, 'message'=>'Plugin with such a name already exists.');
		}
		$this->_uploadPluginName = $namePlugin;

		return array();
	}

	/**
	 * This function deletes a plugin from filesystem.
	 * 
	 * @param string $path
	 * @return void
	 */
	private function _deletePluginFromTmpFolder($path) {
		if(is_dir($path)) {
			$dirHandle = opendir($path);
			if($dirHandle) {
				while(false !== ($file = readdir($dirHandle))) {
					if($file == '.' || $file == '..' || $file == '.svn') {
						continue;
					}
					if(is_dir($path . $file)) {
						$this->_deletePluginFromTmpFolder($path . $file . '/');
					}
					else {
						return unlink($path . $file);
					}
				}
				closedir($dirHandle);
				RCMS_Tools_FilesystemTools::rmDir($path);
			}
		}
	}

	public function disablepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		
		$success = null;
		$websiteUrl = $this->getWebSiteUrl();
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('pluginName')) {
			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));
			if($pluginName) {
				$result = $this->_model->selectPluginByName($pluginName);
				$pluginNameProcessed = str_replace(' ', '-', $pluginName);
				if($result) {
					$pluginObj = new RCMS_Object_Plugin_Plugin($result['id']);
					$pluginObj->setStatus(self::PLUGIN_DISABLED);
					$pluginObj->save();
					$pluginManager = new RCMS_Object_PluginManager_PluginManager($this->_config);
					$pluginManager->removePluginRoute($pluginName);
				}
				echo 'success';
			}
		}
	}

	public function enablepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		
		$flag = true;
		$websiteUrl = $this->getWebSiteUrl();
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('pluginName')) {
			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));
			$pluginNameProcessed = str_replace(' ', '-', $pluginName);
			if($pluginName) {
				$result = $this->_model->selectPluginByName($pluginName);
				if($result) {
					$pluginObj = new RCMS_Object_Plugin_Plugin($result['id']);
					$pluginObj->setStatus(self::PLUGIN_ENABLED);
					$pluginObj->save();
					echo 'success';
				}
				else {
					if(file_exists(RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $pluginName . '/system/install.sql')) {
						$sql = trim(file_get_contents(RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $pluginName . '/system/install.sql'));
						if($sql) {
							$installation = $this->_model->executePluginSql($sql);
							if(!$installation) {
								$flag = true;
								echo 'errors in sql';
								return;
							}
						}
					}
					else {
						$flag = false;
						echo 'install.sql';
						return;
					}

					if($flag) {
						$newPlugin = new RCMS_Object_Plugin_Plugin();
						$newPlugin->setStatus(self::PLUGIN_ENABLED);
						$newPlugin->setName($pluginName);
						$newPlugin->setCache(0);
						$newPlugin->save();
						echo 'success';
					}
				}
			}
		}
	}


	/**
	 * This function deletes a plugin from filesystem.
	 * 
	 * @return void
	 */
	public function deletepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('pluginName') != '') {
			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));
			$pluginPath = $this->_config->website->website->path . RCMS_Object_QuickConfig_QuickConfig::$pluginsDir . $pluginName;
			if(!is_dir($pluginPath)) {
				echo 'Can\'t find plugin directory';
				return;
			}
			$pluginUninstallSqlPath = $pluginPath . '/system/uninstall.sql';
			if(!file_exists($pluginUninstallSqlPath)) {
				echo 'Plugin directory structure is corrupt. Can\'t find uninstall.sql';
				return;
			}
			$uninstallSql = RCMS_Tools_FilesystemTools::getFile($pluginUninstallSqlPath);
			if(trim($uninstallSql) != '') {
				$uninstallResult = $this->_model->executePluginSql($uninstallSql);
				if(!$uninstallResult) {
					echo 'Error in your uninstall.sql';
					return;
				}
			}
			$this->_deletePluginFromTmpFolder($pluginPath);
			$pluginData = $this->_model->selectPluginByName($pluginName);
			if($pluginData) {
				$pluginObj = new RCMS_Object_Plugin_Plugin($pluginData['id']);
				$pluginObj->delete();
			}
			//preg replace content
			$result = $this->_model->selectContentPairs();
			if($result) {
				foreach ($result as $content) {
					$content['value'] = preg_replace('/{\$(plugin:'.$pluginName.'[\w\s-:,]*)}/', '', $content['value']);
					$this->_model->updateContent($content['id'],$content['value']);
				}
			}
			//preg replace tepmlates content
			$result = $this->_model->selectTemplates();
			$filesList = RCMS_Tools_FilesystemTools::scanDir($this->_pathThemes . $this->_currentThemeName);
			if($result) {
				foreach ($result as $template) {
					$template['content'] = preg_replace('/{\$(plugin:'.$pluginName.'[\w\s-:,]*)}/', '', $template['content']);
					$this->_model->updateTemplate($template['id'],$template['content']);
					if(file_exists($this->_pathThemes . $this->_currentThemeName . '/' . $template['name'] . '.html')) {
						file_put_contents($this->_pathThemes.$this->_currentThemeName . '/' . $template['name'] . '.html', $template['content']);
					}
				}
				if(is_dir($pluginPath)) {
					$this->deletePluginFolders($pluginPath);
				}
			}
		}
	}

	public function deletePluginFolders($dir) {
		if (is_dir($dir)) {
			$objects = scandir($dir);
			foreach ($objects as $object) {
				if ($object != "." && $object != "..") {
					if (filetype($dir."/".$object) == "dir") {
							$this->deletePluginFolders($dir."/".$object);
					}
					else {
						unlink($dir."/".$object);
					}
				}
			}
			reset($objects);
			@rmdir($dir);
		} 
	}

	public function fireactionAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pluginName   = $this->getRequest()->getParam('name');
		$pageData     = array('websiteUrl' => $this->getWebSiteUrl());
		try {
			$plugin = RCMS_Core_PluginFactory::createPlugin($pluginName, array(), $pageData);
			$plugin->run($this->getRequest()->getParams());
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
	}
}
